package com.xhg.mqtt.templet;

import com.xhg.mqtt.constant.ResultCodeConstants;
import com.xhg.mqtt.dto.MqttMessagePb;
import com.xhg.mqtt.dto.OnlineStatusPb;
import com.xhg.mqtt.util.CommonUtil;
import com.xhg.mqtt.util.PropertiesUtil;
import com.xhg.mqtt.util.ProtoBufUtil;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;


/**
 * 模拟多线程高并发
 */
public class MultiThreadMqttTest {

    static int count = 0;
    // 总访问量是clientNum，并发量是threadNum
    static int threadNum = 4;
    static int clientNum = 10;
    static String topic = "xhg16100001/server/deviceLogin/440000000000/441900000000/441900004000";
    static String cId = "A";
    static String pId = "xhg16100001";

    float avgExecTime = 0;
    float sumexecTime = 0;
    long firstExecTime = Long.MAX_VALUE;
    long lastDoneTime = Long.MIN_VALUE;
    float totalExecTime = 0;

//    static String[] urls = new String[]{"tcp://premqtt.xhg.com:9099"};
      static String[] urls = new String[]{"tcp://10.10.10.224:1883"};
    private AtomicInteger sendCount = new AtomicInteger(1);
    private AtomicInteger ackCount = new AtomicInteger(0);
    private Map clientMap = new HashMap();

    public static void main(String[] args) {
        if (args.length > 0) {
            urls = new String[]{args[0]};
            threadNum = Integer.parseInt(args[1]);
            clientNum = Integer.parseInt(args[2]);
            topic = String.valueOf(args[3]);
            pId = String.valueOf(args[4]);
            cId = String.valueOf(args[5]);
        }
        new MultiThreadMqttTest().run();
        System.out.println("finished!");
    }

    public void run() {
//    String[] urls = new String[]{"tcp://10.10.10.210:8888"};//接口获取的
//    String[] urls = new String[]{"tcp://premqtt.xhg.com:9099"};//测试环境
        final ConcurrentHashMap<Integer, ThreadRecord> records = new ConcurrentHashMap<Integer, ThreadRecord>();

        // 建立ExecutorService线程池，threadNum个线程可以同时访问
        ExecutorService exec = Executors.newFixedThreadPool(threadNum);
        // 模拟clientNum个客户端访问
        final CountDownLatch doneSignal = new CountDownLatch(clientNum);

        for (int i = 0; i < clientNum; i++) {
            Runnable run = new Runnable() {
                public void run() {
                    int index = getIndex();
                    long systemCurrentTimeMillis = System.currentTimeMillis();
                    try {
//            v2.login();
//            Thread.sleep(50);
//            v2.boxinfo();
                        connect(urls);
//            System.out.println(System.currentTimeMillis());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    records.put(index,
                        new ThreadRecord(systemCurrentTimeMillis, System.currentTimeMillis()));
                    doneSignal.countDown();// 每调用一次countDown()方法，计数器减1
                }
            };
            exec.execute(run);
        }

        try {
            // 计数器大于0 时，await()方法会阻塞程序继续执行
            doneSignal.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /**
         * 获取每个线程的开始时间和结束时间
         */
        for (int i : records.keySet()) {
            ThreadRecord r = records.get(i);
            sumexecTime += ((double) (r.endTime - r.startTime)) / 1000;

            if (r.startTime < firstExecTime) {
                firstExecTime = r.startTime;
            }
            if (r.endTime > lastDoneTime) {
                this.lastDoneTime = r.endTime;
            }
        }

        this.avgExecTime = this.sumexecTime / records.size();
        this.totalExecTime = ((float) (this.lastDoneTime - this.firstExecTime)) / 1000;
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(4);

        System.out.println("======================================================");
        System.out.println("线程数量:\t\t" + threadNum);
        System.out.println("客户端数量:\t" + clientNum);
        System.out.println("发送消息数量:\t" + sendCount.get());
        System.out.println("收到ack数量:\t" + ackCount.get());
        System.out.println("平均执行时间:\t" + nf.format(this.avgExecTime) + "秒");
        System.out.println("总执行时间:\t" + nf.format(this.totalExecTime) + "秒");
        System.out.println("吞吐量:\t\t" + nf.format(this.clientNum / this.totalExecTime) + "次每秒");
        sendMsg();
    }

    public static int getIndex() {
        return ++count;
    }


    public void connect(String[] urls) throws Exception {
        String clientId = CommonUtil.getUUID("");
        MqttClient client = new MqttClient(urls[0], cId + "-" + clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(urls);
        options.setCleanSession(PropertiesUtil.CLEAN_SESSION);
        options.setConnectionTimeout(PropertiesUtil.MQTT_TIMEOUT);
        options.setKeepAliveInterval(PropertiesUtil.MQTT_KEEP_ALIVE);
        //设置自动重连
        options.setAutomaticReconnect(true);
//        options.setMaxInflight(2000);
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("断线了。。。。");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                ackCount.addAndGet(1);
//                System.out.println("接收到服务端ack " + topic);
            System.out.println("接收到服务端ack "+topic+"数量:  【"+ackCount.get()+"】");
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });
        client.connect(options);
        clientMap.put(clientId, client);
//    MqttLoggerFactory.info(MessageFormat.format(MsgConstants.CONNECT_SUCCESS, Arrays.toString(urls)));
    }

    public void sendMsg() {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(() -> {
            try {
                for (Object o : clientMap.keySet()) {
                    String clientId = (String) o;
                    MqttClient client = (MqttClient) clientMap.get(clientId);
                    String dingyue = pId+"/device/" + cId + "-" + clientId + "/ack";
                    //订阅默认消息 qos =1
                    if (client == null) {
                        continue;
                    }
                    client.subscribe(dingyue);
                    //构建业务消息内容
                    OnlineStatusPb.OnlineStatus.Builder online = OnlineStatusPb.OnlineStatus
                        .newBuilder();
                    online.setStatus(1);
                    online.setStatusDesc("[" + clientId + "]" + " 设备上线");
                    //构建消息头
                    MqttMessagePb.MqttHead.Builder head = ProtoBufUtil
                        .builderHead("deviceLogin", clientId, cId + "-" + clientId, "1.0", 1,
                            ResultCodeConstants.SUCCESS, null);
                    //组装消息
                    byte[] bytes = ProtoBufUtil.builderMessage(head, online.build().toByteString());
                    client.publish(topic, bytes, 1, false);
                    System.out.println(
                        "发送成功 数量【"+sendCount.get()+"】-->设备：" + cId + "-" + clientId + " 发送消息【" + clientId + "】到topic->"
                            + topic);
                    sendCount.addAndGet(1);
//            System.out.println("发送消息数->"+sendCount.get());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 1, 3, TimeUnit.SECONDS);
    }

}

class ThreadRecord {

    long startTime;
    long endTime;

    public ThreadRecord(long st, long et) {
        this.startTime = st;
        this.endTime = et;
    }


}